package com.yb.blog.controller;

import com.yb.blog.domain.NavMenu;
import com.yb.blog.domain.Result;
import com.yb.blog.service.NavMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/nav/menu")
public class NavMenuController {

    @Autowired
    private NavMenuService navMenuService;


    @GetMapping("/list")
    public Result list(){
        List<NavMenu> list = navMenuService.getNavMenuList();
        return Result.success(toTree(list));
    }


    private List<NavMenu> toTree(List<NavMenu> list){
        List<NavMenu> resList = new ArrayList<>();
        for(NavMenu menu : list){
            if(menu.getLevel() == 1){
                resList.add(findChildren(menu,list));
            }
        }
        return resList;
    }

    private NavMenu findChildren(NavMenu menu, List<NavMenu> list){
        for(NavMenu c : list){
            if((c.getLevel() == (menu.getLevel() + 1)) && (c.getParentId() == menu.getId())){
                if(menu.getList() == null){
                    menu.setList(new ArrayList<>());
                }
                menu.getList().add(findChildren(c,list));
            }
        }
        return menu;
    }


}
